package com.mapforge.gui.tools;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JToggleButton;

import com.mapforge.listener.TileLayerSelectionEvent;
import com.mapforge.listener.TileLayerSelectionListener;
import com.mapforge.listener.TileWriterChangeEvent;
import com.mapforge.listener.TileWriterChangeListener;
import com.mapforge.listener.TilesetChangeEvent;
import com.mapforge.listener.TilesetChangeListener;
import com.mapforge.map.TileLayer;
import com.mapforge.map.tilewriter.TileWriter;

/**
 * This class is used to represent an interface allowing the user to select a
 * type of tile writer to write selected tiles to some underlying tile layer.
 * 
 * @author Will Morrison
 * 
 */
public class TileWriterButton extends JToggleButton implements
		TileLayerSelectionListener, TilesetChangeListener {

	/**
	 * Default serial version ID, here to remove warnings
	 */
	private static final long serialVersionUID = 1L;

	private TileWriter writer;

	private List<TileWriterChangeListener> tileWriterChangeListeners;

	public TileWriterButton(TileWriter writer, ImageIcon icon, String tooltip) {
		super(icon);
		tileWriterChangeListeners = new ArrayList<TileWriterChangeListener>();
		addActionListener(new TileWriterActionListener());
		setPreferredSize(new Dimension(icon.getIconWidth() + 8, icon
				.getIconHeight() + 8));
		this.setToolTipText(tooltip);
		this.writer = writer;
	}

	public void addTileWriterChangeListener(TileWriterChangeListener listener) {
		tileWriterChangeListeners.add(listener);
	}

	public boolean removeTileWriterChangeListener(
			TileWriterChangeListener listener) {
		return tileWriterChangeListeners.remove(listener);
	}

	public void clearTileWriterChangeListeners() {
		tileWriterChangeListeners.clear();
	}

	public TileWriter getTileWriter() {
		return writer;
	}

	public void setTileWriter(TileWriter writer) {
		this.writer = writer;
	}

	private class TileWriterActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			TileWriterChangeEvent event = new TileWriterChangeEvent(
					TileWriterButton.this, writer);
			for (int i = 0; i < tileWriterChangeListeners.size(); i++) {
				tileWriterChangeListeners.get(i).tileWriterChangePerformed(
						event);
			}
		}
	}

	@Override
	public void tilesetChangePerformed(TilesetChangeEvent event) {
		this.writer.setTileset(event.getNewTileset());
	}

	@Override
	public void tileLayerSelectionPerformed(TileLayerSelectionEvent event) {
		if (event.getNumberLayersSelected() == 1) {
			Iterator<TileLayer> it = event.iterator();
			writer.setTileLayer(it.next());
		} else {
			writer.setTileLayer(null);
		}
	}
}
